package com.sakila.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.sakila.dao.AddressDao;
import com.sakila.dao.MemberDao;
import com.sakila.dao.RoleDao;
import com.sakila.jaas.RoleDefinition;
import com.sakila.pojo.Member;
import com.sakila.pojo.Role;
import com.sakila.pojo.other.Page;
import com.sakila.service.MemberService;
import com.sakila.vo.MemberVo;

@Service
public class MemberServiceImpl implements MemberService {
	@Resource
	private MemberDao memberDao;
	@Resource
	private AddressDao addressDao;
	@Resource
	private RoleDao roleDao;
	
	@Override
	public Member findByUsername(String username) {
		Member member = new Member();
		member.setUsername(username);
		List<Member> list = memberDao.findByProperties(member);
		if(list.size() == 0){
			return null;
		}
		return list.get(0);
	}

	@Override
	public void register(Member member) {
		member.setActive(1);
		member.setCreateDate(new Date());
		
		Set<Role> roles = new HashSet<Role>();
		roles.add(new Role(RoleDefinition.ROLE_MEMBER));
		member.setRoles(roles);
		
		addressDao.save(member.getAddress());
		memberDao.saveCustomer(member);
		memberDao.saveMember(member);
		
		roleDao.saveMemberRoles(member);
	}

	@Override
	public void update(Member member) {
		addressDao.update(member.getAddress());
		memberDao.updateCustomer(member);
		memberDao.updateMember(member);
	}

	@Override
	public Member findByCustomerId(Integer customerId) {
		return memberDao.findByPk(customerId);
	}

	@Override
	public MemberVo findAll(Page page) {
		MemberVo memberVo = new MemberVo();
		memberVo.setList(memberDao.findAll(page));
		memberVo.setTotalNumOfRows(memberDao.getTotalNumOfRows());
		return memberVo;
	}

	@Override
	public MemberVo findByCustomerIdReturnVo(Integer customerId) {
		MemberVo memberVo = new MemberVo();
		List<Member> list = new ArrayList<Member>();
		list.add(memberDao.findByPk(customerId));
		memberVo.setList(list);
		memberVo.setTotalNumOfRows(1L);
		return memberVo;
	}
}
